package com.autonavi.adphoto.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.jcouchdb.db.Database;
import org.jcouchdb.db.ServerImpl;
import org.jcouchdb.document.Attachment;
import org.jcouchdb.document.BaseDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.autonavi.adphoto.entity.Photo;
import com.autonavi.adphoto.entity.Step;
import com.autonavi.adphoto.service.StepService;

@Controller
public class AdPhotoCtrl {
	protected static final Logger logger = LoggerFactory.getLogger(AdPhotoCtrl.class);
	@Autowired
	private StepService stepService;

	@Value("${couchDbUrl}")
	private String couchDbUrl;

	@Value("${couchDbId}")
	private String couchDbId;

	public String getCouchDbId() {
		return couchDbId;
	}

	public void setCouchDbId(String couchDbId) {
		this.couchDbId = couchDbId;
	}

	@RequestMapping(value = "/adphoto/uploadSteps")
	@ResponseBody
	public void uploadSteps(String steps, String photos, @RequestParam
	MultipartFile[] files) throws Exception {
		logger.info("*********************************************");
		logger.info("steps:{}", steps);
		logger.info("photos:{}", photos);
		logger.info("*********************************************");
		if (StringUtils.isBlank(steps) || StringUtils.isBlank(photos) || files == null || files.length == 0) {
			logger.error("Params is error!");
			return;
		}
		List<Step> stepList = JSONArray.parseArray(steps, Step.class);
		if (stepList == null || stepList.isEmpty()) {
			logger.error("Params  steps is error!");
			return;
		}

		List<Photo> photoList = JSONArray.parseArray(photos, Photo.class);
		if (photoList == null || photoList.isEmpty()) {
			logger.error("Params  photos is error!");
			return;
		}

		if (photoList.size() != files.length) {
			logger.error("Params error , photo file num not equal photo info num !");
			return;
		}

		for (int i = 0; i < photoList.size(); i++) {
			savePic(photoList.get(i).getId(), files[i]);
		}
		logger.info("Pic save complete.");
		stepService.save(stepList, photoList);
		logger.info("Db data save complete.");
	}

	private void savePic(String photoId, MultipartFile picFile) throws Exception {
		Database db = new Database(couchDbUrl, couchDbId);
		BaseDocument doc = new BaseDocument();
		try {
			BaseDocument oldDoc = db.getDocument(BaseDocument.class, photoId);
			if (oldDoc != null) {
				doc.setRevision(oldDoc.getRevision());
			}
		} catch (Exception e) {
			logger.debug("", e);
		}

		doc.setId(photoId);
		String contentType = "image/jpg";
		Map<String, Attachment> docMap = new HashMap<String, Attachment>();
		Attachment attach = new Attachment(contentType, picFile.getBytes());
		docMap.put(photoId, attach);
		doc.setAttachments(docMap);
		db.createOrUpdateDocument(doc);
	}

	@PostConstruct
	public void init() {
		logger.info("{} == {} ", couchDbUrl, couchDbId);
		String[] couchDbUrlArr = StringUtils.split(couchDbUrl, ":");
		ServerImpl serverImpl = null;
		if (couchDbUrlArr.length == 1) {
			serverImpl = new ServerImpl(couchDbUrlArr[0]);
		} else if (couchDbUrlArr.length == 2) {
			serverImpl = new ServerImpl(couchDbUrlArr[0], Integer.parseInt(couchDbUrlArr[1]));
		} else {
			logger.error("couchDbUrl :{} error!");
			return;
		}
		if (serverImpl.createDatabase(couchDbId)) {
			logger.info("CouchDb :{} create.", couchDbId);
		} else {
			logger.info("CouchDb :{} exist.", couchDbId);
		}
	}
}
